'use strict';
const Service = require('egg').Service;

class UserinfoController extends Service {
  async getusers (data) {
    console.log('获取用户：', data);
    let sql = 'select * from users';
    const content = [];// 参数
    let isMore = false;// 是否有多个查询参数,只用于搜索查询
    if (data.users_id) {
      sql += ' where users_id = ?';
      content.push(data.users_id);
    }
    if (data.user_nameORusername) {
      sql += ' where concat(username,name) like ?';
      content.push('%' + data.user_nameORusername + '%');
      isMore = true;
    }
    if (data.level) {
      if (isMore) { // true代表有多个参数
        sql += 'and level = ?';// and是两个条件都必须满足，or是或的关系
      } else {
        sql += ' WHERE level = ?';
      }
      content.push(data.level);
      isMore = true;
    }
    if (data.begin && data.end) {
      if (isMore) { // true代表有多个参数
        sql += 'and create_time between ? and ?';// and是两个条件都必须满足，or是或的关系
      } else {
        sql += ' WHERE create_time between ? and ?';
      }
      content.push(data.begin, data.end);
      isMore = true;
    }
    // 开启分页
    if (data.current && data.pageSize) {
      const current = data.current;// 当前页码
      const pageSize = data.pageSize;// 一页展示多少条数据
      sql += ' LIMIT ?,?';
      content.push(parseInt((current - 1) * pageSize), parseInt(pageSize));
    }
    const res = {
      code: 200,
      page: data.current,
      pageSize: data.pageSize,
      data: [],
      total: '',
    };
    res.data = await this.app.mysql.query(
      sql, content
    );
    res.total = await this.app.mysql.count('users');
    return res;
  }
  async getuserinfo (data) {
    // const ctx = this.ctx;
    // console.log('-------', data);
    const username = data.username;
    const password = data.password;
    const res = await this.app.mysql.query('select * from users where username=? and password=?', [username, password]);
    return res;
  }
  // 客户端修改用户信息
  async updateuserinfo (data) {
    console.log('修改用户信息', data);
    const options = {
      where: {
        users_id: data.users_id,
      },
    };
    const res = await this.app.mysql.update('users', data, options);
    return res;
  }
  // 后台修改管理员信息
  async updateadmininfo (data) {
    console.log('修改管理员信息', data);
    const options = {
      where: {
        user_id: data.user_id,
      },
    };
    const res = await this.app.mysql.update('admin_users', data, options);
    return res;
  }
  async deluser (data) {
    console.log('删除用户：', data);
    const where = {
      users_id: data.users_id,
    };
    const res = await this.app.mysql.delete('users', where);
    return res;
  }
}
module.exports = UserinfoController;
